package com.javaclimb.music.config;

import com.javaclimb.music.converter.StringToDateConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * 解决跨域问题
 * */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //addMapping 那些目录允许跨域访问
        //allowedOrigins 允许那些网站
        //allowedMethods 允许那些方法
        //allowCredentials访问时是否需要验证
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    //时间格式问题
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConverter());
    }

    //头像显示问题
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //歌手头像地址
        registry.addResourceHandler("/img/singerPic/**").addResourceLocations(
                "file:" + System.getProperty("user.dir") + System.getProperty("file.separator")
                + "img" + System.getProperty("file.separator") + "singerPic" + System.getProperty("file.separator"));

        //歌曲图片地址
        registry.addResourceHandler("/img/songPic/**").addResourceLocations(
                "file:" + System.getProperty("user.dir") + System.getProperty("file.separator")
                + "img" + System.getProperty("file.separator") + "songPic" + System.getProperty("file.separator"));

        //歌单图片地址
        registry.addResourceHandler("/img/songListPic/**").addResourceLocations(
                "file:" + System.getProperty("user.dir") + System.getProperty("file.separator")
                + "img" + System.getProperty("file.separator") + "songListPic" + System.getProperty("file.separator"));

        //歌曲地址
        registry.addResourceHandler("/song/**").addResourceLocations(
                "file:" + System.getProperty("user.dir") + System.getProperty("file.separator")
                + "song" + System.getProperty("file.separator"));

        //前端用户头像
        registry.addResourceHandler("/avatorImages/**").addResourceLocations(
                "file:" + System.getProperty("user.dir") + System.getProperty("file.separator")
                + "avatorImages" + System.getProperty("file.separator"));
    }
}
